// based on inherites5.js
// sometimes this.__super() not called
// so we not add a closure

// /\b__super\b/.test(prop[name])  ===> is may be cause some bugs
// http://stackoverflow.com/questions/3911690/strange-javascript-idiom-what-does-xyz-testfunctionxyz-do
// fnTest = /xyz/.test(function(){xyz;});
// regex.test(string) => function(){xyz;} will call Function.prototype.toString();
// if toString() result contains 'xyz', 
// means you can use this to test if function contains __super
// else somebody may override Function.prototype.toString() 
initializing = false;
var Class = function() {}

Class.extend = function(prop) {
	var Super = this;

	function F() {
		if (!initializing) { // this should be something {}, after new operator
			this.init.apply(this, arguments);
		}
	}

	// proto chain
	initializing = true;
	F.prototype = new Super();
	initializing = true;
	F.prototype.constructor = F;

	// prop copy
	for (var name in prop) {
		if (typeof(prop[name]) === 'function' && typeof(Super.prototype[name]) === 'function'
			// if this.__super() is called in sub,we should create the closure
			// how to check? if '__super' exist, we believe it call the super method
			&& /\b__super\b/.test(prop[name])
		) {
			F.prototype[name] = (function(name, fn) {
				return function() {
					var tmp = this.__super;
					this.__super = Super.prototype[name];
					var ret = fn.apply(this, arguments);
					this.__super = tmp;
					return ret;
				}
			})(name, prop[name]);
		} else {
			F.prototype[name] = prop[name];
		}
	}

	F.extend = arguments.callee;
	return F;
}

var Person = Class.extend({
	init: function(name) {
		this.name = name;
	},
	getName: function() {
		return this.name;
	}
});

var Teacher = Person.extend({
	init: function(name, age) {
		this.__super(name);
		this.age = age;
	},
	getName: function() {
		return "teacher:" + this.__super();
	}
});

var t1 = new Teacher("abc", 12);
console.log(t1.getName());

var t2 = new Teacher("aaa", 12);
console.log(t2.getName());